import java.util.LinkedList;
import java.util.Scanner;

public class Administrator extends Users implements LogIn {
    // 在类顶部添加常量，用于指定日志文件路径
    private static final String LOG_FILE_PATH = "password_change_log.txt";

    public Administrator() {
    }

    public Administrator(String ID, String name, String password, String registrationDate, String role, String phoneNumber) {
        super(ID, name, password, registrationDate, role, phoneNumber);
    }


    @Override
    public boolean logIn(String name, String password) {
        // 从管理员列表中查找匹配的用户名和密码
        CinemaSystem cinemaSystem = CinemaSystem.getInstance();
        for (Administrator admin : cinemaSystem.getAdminList()) {
            if (admin.getName().equals(name) && admin.getPassword().equals(password)) {
                return true;
            }
        }
        return false;
    }


    //修改管理员密码
    @Override
    public void changePassword(String newPassword) {
        if (newPassword == null || newPassword.trim().isEmpty()) {
            System.out.println("错误：新密码不能为空！");
            return;
        }

        // 获取当前登录管理员
        CinemaSystem cinemaSystem = CinemaSystem.getInstance();
        Users currentUser = cinemaSystem.getCurrentUser();
        if (currentUser != null && currentUser instanceof Administrator) {
            currentUser.setPassword(newPassword);
            cinemaSystem.saveUserData(); // 保存到文件
            System.out.println("密码修改成功！");
        } else {
            System.out.println("错误：未找到当前管理员！");
        }
    }

    //重置经理或前台密码
    @Override
    public void resetPassword() {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请选择要重置密码的用户类型：");
        System.out.println("1. 经理");
        System.out.println("2. 前台");
        int choice = scanner.nextInt();

        CinemaSystem cinemaSystem = CinemaSystem.getInstance();
        String targetRole = "";
        LinkedList<? extends Users> targetList = null;

        switch (choice) {
            case 1:
                targetRole = "经理";
                targetList = cinemaSystem.getManagerList();
                break;
            case 2:
                targetRole = "前台";
                targetList = cinemaSystem.getFrontDeskReceptionList();
                break;
            default:
                System.out.println("无效选择！");
                return;
        }

        System.out.println("请输入要重置密码的用户名字：");
        String targetName = scanner.next();
        //找到对应名字的ID
        String targetID = "";
        for (Users u : targetList) {
            if (u.getName().equals(targetName)) {
                targetID = u.getID();
                break;
            }
        }

        //操作人姓名输入
        System.out.println("请输入操作人姓名：");
        String operatorName = scanner.nextLine();
        //找到操作人姓名对应的ID
        String operatorID = "";
        for (Users u : targetList) {
            if (u.getName().equals(operatorName)) {
                operatorID = u.getID();
                break;
            }
        }

        boolean found = false;
        for (Users user : targetList) {
            if (user.getID().equals(targetID)) {
                // 生成默认密码
                String defaultPassword = "123456";
                user.setPassword(defaultPassword);
                found = true;
                break;
            }
        }

        getOperatorInfo();
        System.out.println(found ? "密码重置成功！默认密码为：123456" : "错误：未找到该用户！");
    }


    //列出所有管理员的信息
    @Override
    public void listAllUsers() {
        CinemaSystem cinemaSystem = CinemaSystem.getInstance();
        LinkedList<Administrator> admins = cinemaSystem.getAdminList();
        for (Administrator admin : admins) {
            System.out.println("ID: " + admin.getID() + ", 姓名: " + admin.getName() + ", 注册日期: " + admin.getRegistrationDate() + ", 角色: " + admin.getRole() + ", 电话: " + admin.getPhoneNumber());
        }
    }


    //删除管理员/经理/前台的信息
    @Override
    public void deleteUser() {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请选择要删除的用户类型：");
        System.out.println("1. 管理员");
        System.out.println("2. 经理");
        System.out.println("3. 前台");
        int choice = scanner.nextInt();

        CinemaSystem cinemaSystem = CinemaSystem.getInstance();
        String targetRole = "";
        LinkedList<? extends Users> targetList = null;

        switch (choice) {
            case 1:
                targetRole = "管理员";
                targetList = cinemaSystem.getAdminList();
                break;
            case 2:
                targetRole = "经理";
                targetList = cinemaSystem.getManagerList();
                break;
            case 3:
                targetRole = "前台";
                targetList = cinemaSystem.getFrontDeskReceptionList();
                break;
            default:
                System.out.println("无效选择！");
                return;
        }

        System.out.println("请输入要删除的用户名字：");
        String targetName = scanner.next();
        //找到对应名字的用户并获取ID
        String targetID = "";
        boolean isSuperAdmin = false;
        for (Users u : targetList) {
            if (u.getName().equals(targetName)) {
                targetID = u.getID();
                // 检查是否为超级管理员
                if ("admin".equals(u.getName())) {
                    isSuperAdmin = true;
                }
                break;
            }
        }

        if (isSuperAdmin) {
            System.out.println("错误：不能删除超级管理员账户！");
            return;
        }

        // 警告提示
        System.out.println("警告：您确定要删除" + targetRole + "姓名为" + targetName + "ID为" + targetID + "的用户吗？(y/n)");
        String confirm = scanner.next();

        boolean found = false;
        if (!"y".equalsIgnoreCase(confirm)) {
            System.out.println("已取消删除操作");
            return;
        }else{
            //删除对应ID的用户
            for (Users user : targetList) {
                if (user.getID().equals(targetID)) {
                    targetList.remove(user);
                    found = true;
                    break;
                }
            }
        }

        getOperatorInfo();
        System.out.println(found ? "用户删除成功！" : "错误：未找到该用户！");
    }

    //查询管理员/经理/前台的信息
    @Override
    public void searchUser() {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请选择查询方式：");
        System.out.println("1. 按ID查询");
        System.out.println("2. 按用户名查询");
        System.out.println("3. 查询所有用户");
        int choice = scanner.nextInt();
        scanner.nextLine(); // 消耗换行符

        CinemaSystem cinemaSystem = CinemaSystem.getInstance();
        LinkedList<? extends Users> usersToSearch = null;

        // 获取要查询的用户类型
        System.out.println("请选择用户类型：");
        System.out.println("1. 管理员");
        System.out.println("2. 经理");
        System.out.println("3. 前台");
        int userType = scanner.nextInt();
        scanner.nextLine(); // 消耗换行符
        //获得要查询的用户类型链表
        switch (userType) {
            case 1:
                usersToSearch = cinemaSystem.getAdminList();
                break;
            case 2:
                usersToSearch = cinemaSystem.getManagerList();
                break;
            case 3:
                usersToSearch = cinemaSystem.getFrontDeskReceptionList();
                break;
            default:
                System.out.println("无效选择！");
                return;
        }

        boolean found = false;
        switch (choice) {
            case 1: // 按ID查询
                System.out.println("请输入要查询的用户ID：");
                String targetID = scanner.nextLine();
                for (Users user : usersToSearch) {
                    if (user.getID().equals(targetID)) {
                        System.out.println("查询结果：");
                        System.out.println("ID: " + user.getID() + ", 姓名: " + user.getName() + ", 注册日期: " + user.getRegistrationDate() + ", 角色: " + user.getRole() + ", 电话: " + user.getPhoneNumber());
                        found = true;
                        break;
                    }
                }
                break;

            case 2: // 按用户名查询
                System.out.println("请输入要查询的用户名：");
                String targetName = scanner.nextLine();
                for (Users user : usersToSearch) {
                    if (user.getName().equals(targetName)) {
                        System.out.println("查询结果：");
                        System.out.println("ID: " + user.getID() + ", 姓名: " + user.getName() + ", 注册日期: " + user.getRegistrationDate() + ", 角色: " + user.getRole() + ", 电话: " + user.getPhoneNumber());
                        found = true;
                    }
                }
                break;

            case 3: // 查询所有用户
                System.out.println("所有用户信息：");
                for (Users user : usersToSearch) {
                    System.out.println("ID: " + user.getID() + ", 姓名: " + user.getName() + ", 注册日期: " + user.getRegistrationDate() + ", 角色: " + user.getRole() + ", 电话: " + user.getPhoneNumber());
                    found = true;
                }
                break;

            default:
                System.out.println("无效选择！");
                return;
        }

        if (!found && choice != 3) {
            System.out.println("未找到匹配的用户！");
        }
    }

    //增加管理员/经理/前台的信息
    @Override
    public void addUser() {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请选择要添加的用户类型：");
        System.out.println("1. 管理员");
        System.out.println("2. 经理");
        System.out.println("3. 前台");
        int choice = scanner.nextInt();
        scanner.nextLine(); // 消耗换行符

        CinemaSystem cinemaSystem = CinemaSystem.getInstance();
        LinkedList<? extends Users> targetList = null;
        String role = "";

        switch (choice) {
            case 1:
                role = "管理员";
                targetList = cinemaSystem.getAdminList();
                break;
            case 2:
                role = "经理";
                targetList = cinemaSystem.getManagerList();
                break;
            case 3:
                role = "前台";
                targetList = cinemaSystem.getFrontDeskReceptionList();
                break;
            default:
                System.out.println("无效选择！");
                return;
        }

        // 自动生成用户ID
        String ID;
        do {
            // 生成6位随机数字ID
            ID = String.format("%06d", (int) (Math.random() * 1000000));
            // 检查ID是否已存在
            boolean exists = false;
            for (Users user : targetList) {
                if (user.getID().equals(ID)) {
                    exists = true;
                    break;
                }
            }
            if (!exists) break;
        } while (true);

        System.out.println("系统生成的用户ID为: " + ID);
        System.out.println("请输入用户名：");
        String name = scanner.nextLine();
        System.out.println("请输入手机号：");
        String phoneNumber = scanner.nextLine();

        // 自动获取当前日期作为注册日期
        String registrationDate = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new java.util.Date());

        // 唯一性检查
        for (Users user : targetList) {
            if (user.getID().equals(ID)) {
                System.out.println("错误：用户ID已存在！");
                return;
            }
            if (user.getName().equals(name)) {
                System.out.println("错误：用户名已存在！");
                return;
            }
            if (user.getPhoneNumber().equals(phoneNumber)) {
                System.out.println("错误：手机号已存在！");
                return;
            }
        }


        // 设置默认密码
        String defaultPassword = "123456";

        // 创建新用户
        Users newUser = null;
        // 修改添加用户的部分
        switch (choice) {
            case 1:
                newUser = new Administrator(ID, name, defaultPassword, registrationDate, role, phoneNumber);
                //添加到对应链表
                cinemaSystem.getAdminList().add((Administrator) newUser);
                break;
            case 2:
                newUser = new Manager(ID, name, defaultPassword, registrationDate, role, phoneNumber);
                cinemaSystem.getManagerList().add((Manager) newUser);
                break;
            case 3:
                newUser = new FrontDeskReception(ID, name, defaultPassword, registrationDate, role, phoneNumber);
                cinemaSystem.getFrontDeskReceptionList().add((FrontDeskReception) newUser);
                break;
        }

        getOperatorInfo();

        System.out.println("用户添加成功！默认密码为：123456");
    }


    //修改经理/前台的信息（用户类型和用户手机号）
    @Override
    public void modifyUser() {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请选择要修改的用户类型：");
        System.out.println("1. 经理");
        System.out.println("2. 前台");
        int choice = scanner.nextInt();
        scanner.nextLine(); // 消耗换行符

        CinemaSystem cinemaSystem = CinemaSystem.getInstance();
        LinkedList<? extends Users> targetList = null;
        String role = "";

        switch (choice) {
            case 1:
                role = "经理";
                targetList = cinemaSystem.getManagerList();
                break;
            case 2:
                role = "前台";
                targetList = cinemaSystem.getFrontDeskReceptionList();
                break;
            default:
                System.out.println("无效选择！只能修改经理或前台信息");
                return;
        }

        System.out.println("请输入要修改的用户ID：");
        String targetID = scanner.nextLine();

        boolean found = false;
        for (Users user : targetList) {
            if (user.getID().equals(targetID)) {
                System.out.println("当前用户信息：");
                System.out.println("ID: " + user.getID() + ", 姓名: " + user.getName() + ", 注册日期: " + user.getRegistrationDate() + ", 角色: " + user.getRole() + ", 电话: " + user.getPhoneNumber());

                // 询问要修改的字段
                System.out.println("请选择要修改的内容：");
                System.out.println("1. 用户类型");
                System.out.println("2. 手机号");
                System.out.println("3. 两者都修改");
                int modifyChoice = scanner.nextInt();
                scanner.nextLine(); // 消耗换行符

                String newRole = "";
                String newPhoneNumber = user.getPhoneNumber();

                // 修改用户类型
                if (modifyChoice == 1 || modifyChoice == 3) {
                    // 自动转换角色：经理<->前台
                    newRole = user.getRole().equals("经理") ? "前台" : "经理";
                    System.out.println("将自动转换为: " + newRole);
                    if (!newRole.equals("经理") && !newRole.equals("前台")) {
                        System.out.println("错误：只能修改为经理或前台！");
                        return;
                    }

                    // 修改完用户类型后，应当把该用户从原来所在链表删除，再添加到新的链表中
                    targetList.remove(user);

                    // 创建新用户对象而不是强制转换
                    if (newRole.equals("经理")) {
                        Manager newManager = new Manager(user.getID(), user.getName(), "123456", user.getRegistrationDate(), newRole, user.getPhoneNumber());
                        cinemaSystem.getManagerList().add(newManager);
                    } else {
                        FrontDeskReception newFrontDesk = new FrontDeskReception(user.getID(), user.getName(), "123456", user.getRegistrationDate(), newRole,
                                user.getPhoneNumber());
                        cinemaSystem.getFrontDeskReceptionList().add(newFrontDesk);
                    }
                }

                // 修改手机号
                if (modifyChoice == 2 || modifyChoice == 3) {
                    System.out.println("请输入新的手机号：");
                    newPhoneNumber = scanner.nextLine();

                    // 检查手机号唯一性
                    for (Users u : targetList) {
                        if (u != user && u.getPhoneNumber().equals(newPhoneNumber)) {
                            System.out.println("错误：手机号已存在！");
                            return;
                        }
                    }
                }

                // 更新信息
                user.setRole(newRole);
                user.setPhoneNumber(newPhoneNumber);

                // 保存修改后的数据
                cinemaSystem.saveUserData();
                getOperatorInfo();

                found = true;
                break;
            }
        }

        System.out.println(found ? "用户信息修改成功！" : "错误：未找到该用户！");
    }


    // 新增方法：获取操作人信息并返回操作人姓名和ID,并且将操作人的信息记入日志文件中
    public String[] getOperatorInfo() {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入操作人姓名或ID：");
        String input = scanner.nextLine();

        // 在所有用户列表中查找操作人
        CinemaSystem cinemaSystem = CinemaSystem.getInstance();
        String operatorName = "";
        String operatorID = "";


        // 让管理员直接输入操作类型
        System.out.println("请输入操作类型（如：修改密码、重置密码等）：");
        String operationType = scanner.nextLine();

        // 在管理员列表中查找
        for (Users u : cinemaSystem.getAdminList()) {
            if (u.getID().equals(input) || u.getName().equals(input)) {
                operatorName = u.getName();
                operatorID = u.getID();
                break;
            }
        }

        // 如果没找到，在经理列表中查找
        if (operatorName.isEmpty()) {
            for (Users u : cinemaSystem.getManagerList()) {
                if (u.getID().equals(input) || u.getName().equals(input)) {
                    operatorName = u.getName();
                    operatorID = u.getID();
                    break;
                }
            }
        }

        // 如果还没找到，在前台列表中查找
        if (operatorName.isEmpty()) {
            for (Users u : cinemaSystem.getFrontDeskReceptionList()) {
                if (u.getID().equals(input) || u.getName().equals(input)) {
                    operatorName = u.getName();
                    operatorID = u.getID();
                    break;
                }
            }
        }

        if (operatorName.isEmpty()) {
            System.out.println("警告：未找到匹配的操作人信息，将使用默认值");
            operatorName = "未知";
            operatorID = "000000";
        }

        // 记录日志
        String timestamp = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new java.util.Date());
        String logEntry = String.format("时间: %s, 操作类型: %s, 操作人: %s, 操作人ID: %s", timestamp, operationType, operatorName, operatorID);

        // 输出到控制台
        System.out.println("\n========== 操作信息记录 ==========");
        System.out.println("操作时间: " + timestamp);
        System.out.println("操作类型: " + operationType);
        System.out.println("操作人: " + operatorName);
        System.out.println("操作人ID: " + operatorID);
        System.out.println("===============================\n");

        // 写入日志文件
        try (java.io.PrintWriter out = new java.io.PrintWriter(new java.io.FileWriter(LOG_FILE_PATH, true))) {
            out.println(logEntry);
        } catch (java.io.IOException e) {
            System.err.println("无法写入日志文件: " + e.getMessage());
        }

        return new String[]{operatorName, operatorID, operationType};

    }


    // 在Administrator类中添加一个清空日志的方法
    public void clearLogFile() {
        try (java.io.PrintWriter out = new java.io.PrintWriter(
                new java.io.FileWriter(Administrator.LOG_FILE_PATH, false))) {
            // 使用false参数会覆盖文件内容
            System.out.println("日志文件已清空");
        } catch (java.io.IOException e) {
            System.err.println("无法清空日志文件: " + e.getMessage());
        }
    }

}

